package com.example.w.weather_demo;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private String baseUrl = "https://free-api.heweather.com/v5/";
    private String urlCity = "search";
    private String urForecast = "forecast";

    private EditText et;
    private Button search;
    private TextView tv;
    private Gson gson;
    private LocationManager manager;
    private Button getLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (gson == null) {
            gson = new Gson();
        }
        initView();
        initLocation();
    }

    private void initLocation() {
        et.setText("定位中...");
        manager = LocationManager.init(this)
                .setListener(new LocationManager.LocationManagerListener() {
                    @Override
                    public void getInfo(String province, String city) {
                        et.setText(city);
                    }
                })
                .startLocation();

    }


    @Override
    protected void onStop() {
        super.onStop();
        manager.stopLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.destoryLocation();
    }

    private void initView() {
        et = (EditText) findViewById(R.id.et);
        search = (Button) findViewById(R.id.search);
        search.setOnClickListener(this);
        getLocation = (Button) findViewById(R.id.getLocation);
        getLocation.setOnClickListener(this);
        tv = (TextView) findViewById(R.id.tv);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search:
                search();
                break;
            case R.id.getLocation:
                getLocation();
                break;
        }
    }

    private void getLocation() {
        et.setText("定位中...");
        manager.startLocation();
    }

    private void search() {
        tv.setText("");
        String cityName = et.getText().toString().trim();
        if (!TextUtils.isEmpty(cityName)) {
            searchCity(cityName);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }

        } else {
            Toast.makeText(MainActivity.this, "请输入想要查询的城市名称", Toast.LENGTH_SHORT).show();
        }
    }

    String cityId;

    //根据城市名称查询城市id
    private void searchCity(String cityName) {

        OkGo.get(baseUrl + urlCity)
                .tag(this)
                .params("city", cityName)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LoggerUtils.e("城市id获取成功" + s);

                        CityInfo cityInfo = gson.fromJson(s, CityInfo.class);
                        List<CityInfo.HeWeather5> cityList = cityInfo.HeWeather5;

                        for (CityInfo.HeWeather5 c : cityList) {
                            String status = c.status;
                            if (TextUtils.equals("ok", status)) {
                                CityInfo.HeWeather5.Basic basic = c.basic;
                                LoggerUtils.e("城市为:" + basic.city + "," + basic.cnty + ";id:" + (cityId = basic.id));
                                forecast(cityId);
                            } else {
                                Toast.makeText(MainActivity.this, "没有找到该城市,请重新填写", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        LoggerUtils.e("城市id获取错误");
                        Toast.makeText(MainActivity.this, "网络连接错误", Toast.LENGTH_SHORT).show();
                        super.onError(call, response, e);
                    }
                });
    }

    StringBuilder sb;

    //根据城市id查询天气预报
    private void forecast(String cityId) {
        sb = new StringBuilder();
        OkGo.get(baseUrl + urForecast)
                .tag(this)
                .params("city", cityId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LoggerUtils.e("天气预报信息获取成功");
                        WeatherInfo weatherInfo = gson.fromJson(s, WeatherInfo.class);
                        List<WeatherInfo.HeWeather5> heWeather5 = weatherInfo.HeWeather5;
                        for (WeatherInfo.HeWeather5 w : heWeather5) {
                            String status = w.status;
                            if (TextUtils.equals("ok", status)) {
                                WeatherInfo.HeWeather5.Basic basic = w.basic;
                                sb.append("城市名称:" + basic.city);
                                sb.append("\r\n");
                                sb.append("更新时间:" + basic.update.loc);
                                sb.append("\r\n");
                                sb.append("------------------------");
                                sb.append("\r\n");

                                List<WeatherInfo.HeWeather5.DailyForecast> daily_forecast = w.daily_forecast;
                                for (WeatherInfo.HeWeather5.DailyForecast d : daily_forecast) {
                                    WeatherInfo.HeWeather5.DailyForecast.Cond cond = d.cond;
                                    sb.append("白天天气状况:" + cond.txt_d);
                                    sb.append("\r\n");
                                    sb.append("夜间天气状况:" + cond.txt_n);
                                    sb.append("\r\n");
                                    sb.append("预报日期:" + d.date);
                                    sb.append("\r\n");
                                    sb.append("相对湿度:" + d.hum + "%");
                                    sb.append("\r\n");
                                    sb.append("降水概率:" + d.pop + "%");
                                    sb.append("\r\n");
                                    sb.append("最高温度:" + d.tmp.max + "℃");
                                    sb.append("\r\n");
                                    sb.append("最低温度:" + d.tmp.min + "℃");
                                    sb.append("\r\n");
                                    sb.append("能见度:" + d.vis + "km");
                                    sb.append("\r\n");
                                    sb.append("------------------------");
                                    sb.append("\r\n");
                                }
                            }
                        }

                        String txt = sb.toString();
                        tv.setText(txt);
                    }
                });
    }
}


